package com.supor.aiot.food.ui.food;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.android.baseconfig.base.BaseApiResult;
import com.android.baseconfig.base.RxBus3;
import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.supor.aiot.common.app.AppAgent;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.app.SuporPresenter;
import com.supor.aiot.common.arouter.PathUrl;
import com.supor.aiot.common.base.BaseLocalConfigBean;
import com.supor.aiot.common.base.BaseMVVMFragment;
import com.supor.aiot.common.helper.GlobalDataCache;
import com.supor.aiot.common.ui.scan.ScanHelper;
import com.supor.aiot.food.R;
import com.supor.aiot.food.adapter.RecipeChefAdapter;
import com.supor.aiot.food.adapter.RecipeDeviceAdapter;
import com.supor.aiot.food.adapter.RecipeHotAdapter;
import com.supor.aiot.food.adapter.RecipeNoneResultAdapter;
import com.supor.aiot.food.adapter.RecipeTopicAdapter;
import com.supor.aiot.food.adapter.RecomondRecipeAdapter;
import com.supor.aiot.food.api.SearchFoodImpl;
import com.supor.aiot.food.bean.BindDeviceBean;
import com.supor.aiot.food.bean.ChefDetailBean;
import com.supor.aiot.food.bean.ChildListBean;
import com.supor.aiot.food.bean.RecipeHotBean;
import com.supor.aiot.food.bean.RecipeStoreBean;
import com.supor.aiot.food.bean.RecipeTopicBean;
import com.supor.aiot.food.databinding.FoodFragmentRootBinding;
import com.supor.aiot.food.utils.DoubleClickUtils;
import com.supor.md_video.api.VideoApiImpl;
import com.supor.md_video.entity.FavoritStateBean;
import com.supor.md_video.entity.VideoFavoritBean;
import com.supor.md_video.tools.NumberUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class FoodRootFragment extends BaseMVVMFragment<FoodViewModel, FoodFragmentRootBinding> implements View.OnClickListener {
    public final static int INDEX_IN_HOME = 2;//计数从1开始
    private FoodViewModel mViewModel;
    //    private List<RecipeHotBean> mRecomondList = new ArrayList<>();
    private List<RecipeTopicBean> mTopicList = new ArrayList<>();
    private List<ChefDetailBean> mCookerList = new ArrayList<>();
    private List<BindDeviceBean> mDeviceList = new ArrayList<>();
    private List<RecipeHotBean> mHotList = new ArrayList<>();
    private List<ChildListBean> mClassifyList = new ArrayList<>();
    private RecomondRecipeAdapter recipeAdapter;
    private RecipeTopicAdapter topicAdapter;
    private RecipeChefAdapter cookerAdapter;
    private RecipeDeviceAdapter deviceAdapter;
    private RecipeHotAdapter hotAdapter;
    private RecipeNoneResultAdapter noneResultAdapter;
    private String deviceProductModel = "";
    private int StatePositon = 1;
    private int originHotPage = 1;
    private int originNewPage = 1;
    private String recomondWord;

    private ImageView ivRecipeAll;
    private ImageView ivFruitEggs;
    private ImageView ivMainFood;
    private ImageView ivMeatMean;
    private ImageView ivSeaFood;
    private TextView edtFoodInput;
    private ImageView ivScan;
    private RecyclerView rvRecordRecipe;
    private RecyclerView rvRecipeClass;
    private RecyclerView rvRecipeCooker;
    private RecyclerView rvRecipeDevice;
    private TextView tvRecipeHot;
    private TextView tvRecipeNew;
    private View rlNoneResult;
//    private SmartRefreshHorizontal smartRefreshHorizontal;

    public static FoodRootFragment newInstance() {
        return new FoodRootFragment();
    }

    private static final String CLASSIFY_POSITION = "CLASSIFY_POSITION";
    private static final String CLASSIFY_DATA = "CLASSIFY_DATA";
    private static final String CHEF_ID = "CHEF_ID";
    private static final String RECOMOND_WORD = "RECOMOND_WORD";
    private static final String CLASSIFY_SECOND_DATA = "CLASSIFY_SECOND_DATA";
    private static final String CLASSIFY_SECOND_POSITION = "CLASSIFY_SECOND_POSITION";


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = new ViewModelProvider(this).get(FoodViewModel.class);
        initRecycleView();
        initCommondClick();
        initOriginState();
        RxBus3.getInstance().register(Constants.Tag.LOGIN, (Consumer<String>) s -> {
            if (Constants.Value.SUCCESS.equalsIgnoreCase(s)) {
                initOriginState();
            }
        }, this.getClass());
    }

    private void initOriginState() {
        initAllClassify();
        initChefList();
        initDevice();
        initNewRecomond();
        initVedioRecipe();
        initFoodRecomonds();
        deviceProductModel = "";
        initHotRecipe(deviceProductModel);
        bindingView.refreshLayouthead.finishRefresh();
    }

    private void initCommondClick() {
        ivRecipeAll.setOnClickListener(this);
        ivFruitEggs.setOnClickListener(this);
        ivMainFood.setOnClickListener(this);
        ivMeatMean.setOnClickListener(this);
        ivSeaFood.setOnClickListener(this);
        edtFoodInput.setOnClickListener(this);
        ivScan.setOnClickListener(this);

        bindingView.refreshLayouthead.setOnLoadMoreListener(refreshLayout -> {
            if (StatePositon == 1) {
                originHotPage++;
                initHotRecipe(deviceProductModel);
            } else {
                originNewPage++;
                initNewRecipe(deviceProductModel);
            }
        });

        bindingView.refreshLayouthead.setEnableRefresh(true);
        bindingView.refreshLayouthead.setEnableLoadMore(true);
        bindingView.refreshLayouthead.setOnRefreshListener(refreshLayout -> initOriginState());
        bindingView.refreshLayouthead.setRefreshHeader(new ClassicsHeader(getActivity()));
        bindingView.refreshLayouthead.setRefreshFooter(new ClassicsFooter(getActivity()));
    }

    private void initDevice() {
        getUnbindDevice();
    }

    private void gotoScanActivity() {
        ScanHelper.getInstance().scan(getActivity(), new ScanHelper.ScanCallback() {
            @Override
            public void onScanResult(boolean isProcessed, Intent result) {
                if (!isProcessed) {
                    // 扫码界面点击物理返回键或左上角返回键
                    return;
                }

                // 注意：本回调是在子线程中执行
                getActivity().runOnUiThread(() -> {
                    if (result == null || result.getData() == null) {
                        // 扫码失败
                        return;
                    }
                    // 扫码成功
                    String url = result.getData().toString();
                    Logc.d("scan url: " + url);
                    //initSearch(url);
                    ToastUtils.getInstance().showCustomToast(getResources().getString(R.string.error_scan_result));
                });
            }
        });
    }

    @SuppressLint("AutoDispose")
    private void initHotRecipe(String productModel) {
        SearchFoodImpl.getInstance().getHotRecipeFood(productModel, originHotPage, 20).subscribe(result -> {
            if (result.data.rows.size() == 0) {
                if (bindingView.rvRecipeList.getFooterCount() == 0)
                    bindingView.rvRecipeList.addFooterView(rlNoneResult);
                mHotList.clear();
                hotAdapter.notifyDataSetChanged();
                bindingView.refreshLayouthead.setEnableLoadMore(false);
            } else {
                bindingView.refreshLayouthead.setEnableLoadMore(true);
                if (originHotPage == 1) {
                    mHotList.clear();
                }
                if (mHotList.size() < result.total) {
                    mHotList.addAll(result.data.rows);
                }
                if (bindingView.rvRecipeList.getFooterCount() > 0)
                    bindingView.rvRecipeList.removeFooterView(rlNoneResult);
                hotAdapter.notifyDataSetChanged();
            }
            bindingView.refreshLayouthead.finishLoadMore();
        }, throwable -> {
            ToastUtils.getInstance().showCustomToast(getActivity().getResources().getString(R.string.get_hotrecipe_error) + throwable.getMessage());
            mHotList.clear();
            if (bindingView.rvRecipeList.getFooterCount() == 0)
                bindingView.rvRecipeList.addFooterView(rlNoneResult);
            hotAdapter.notifyDataSetChanged();
            bindingView.refreshLayouthead.finishLoadMore();
            bindingView.refreshLayouthead.setEnableLoadMore(false);
        });
    }

    @SuppressLint("AutoDispose")
    private void initNewRecipe(String productModel) {
        SearchFoodImpl.getInstance().getNewRecipe(productModel, originNewPage, 20).subscribe(result -> {
            if (result.data.rows.size() == 0) {
                if (bindingView.rvRecipeList.getFooterCount() == 0)
                    bindingView.rvRecipeList.addFooterView(rlNoneResult);
                mHotList.clear();
                hotAdapter.notifyDataSetChanged();
                bindingView.refreshLayouthead.setEnableLoadMore(false);
            } else {
                bindingView.refreshLayouthead.setEnableLoadMore(true);
                if (originNewPage == 1) {
                    mHotList.clear();
                }
                if (mHotList.size() < result.total) {
                    mHotList.addAll(result.data.rows);
                }
                if (bindingView.rvRecipeList.getFooterCount() > 0)
                    bindingView.rvRecipeList.removeFooterView(rlNoneResult);
                hotAdapter.notifyDataSetChanged();
            }
            bindingView.refreshLayouthead.finishLoadMore();
        }, throwable -> {
            ToastUtils.getInstance().showCustomToast(getActivity().getResources().getString(R.string.get_hotrecipe_error) + throwable.getMessage());
            mHotList.clear();
            if (bindingView.rvRecipeList.getFooterCount() == 0)
                bindingView.rvRecipeList.addFooterView(rlNoneResult);
            hotAdapter.notifyDataSetChanged();
            bindingView.refreshLayouthead.finishLoadMore();
            bindingView.refreshLayouthead.setEnableLoadMore(false);
        });
    }


    @SuppressLint("AutoDispose")
    private void initNewRecomond() {
        recomondWord = getActivity().getResources().getString(R.string.default_recomond);
        SearchFoodImpl.getInstance().getNewRecomond().subscribe(result -> {
            if (result.isSuccess()) {
                if (!TextUtils.isEmpty(result.data.rows.get(0).getRecipeName())) {
                    recomondWord = result.data.rows.get(0).getRecipeName();
                    edtFoodInput.setText(recomondWord);
                }
                ;
            } else {
                ToastUtils.getInstance().showCustomToast(result.message);
                edtFoodInput.setText(recomondWord);
            }
        }, throwable -> {
            ToastUtils.getInstance().showCustomToast(throwable.getMessage());
            edtFoodInput.setText(recomondWord);
        });
    }


    /**
     * 查询所有分类列表
     */
    @SuppressLint("AutoDispose")
    private void initAllClassify() {
        SearchFoodImpl.getInstance().getAllClassify("APP_CLASSIFACTION",50).subscribe(result -> {
            if (result.isSuccess()) {
                mClassifyList.clear();
                for (int i = 0; i < result.data.rows.size(); i++) {
                    if (result.data.rows.get(i).getClassificationName().equals(getActivity().getResources().getString(R.string.recipe_hot))) {
                        mClassifyList.add(result.data.rows.get(i));
                    }
                }
                for (int i = 0; i < result.data.rows.size(); i++) {
                    if (result.data.rows.get(i).getClassificationName().equals(getActivity().getResources().getString(R.string.device_recipe))) {
                        mClassifyList.add(result.data.rows.get(i));
                    }
                }

                for (int i = 0; i < result.data.rows.size(); i++) {
                    if (!mClassifyList.contains(result.data.rows.get(i))) {
                        mClassifyList.add(result.data.rows.get(i));
                    }
                }

            } else {
                ToastUtils.getInstance().showCustomToast(result.message);
            }
        }, throwable -> {
            ToastUtils.getInstance().showCustomToast(throwable.getMessage());
        });
    }

    /**
     * 星厨秀
     */
    @SuppressLint("AutoDispose")
    private void initChefList() {
        SearchFoodImpl.getInstance().getChefList(1, 200).subscribe(result -> {
            if (result.isSuccess()) {
                mCookerList.clear();
                mCookerList.addAll(result.data.rows);
                cookerAdapter.notifyDataSetChanged();
            } else {
                ToastUtils.getInstance().showCustomToast(result.message);
            }

        }, throwable -> {
            ToastUtils.getInstance().showCustomToast(throwable.getMessage());
        });
    }


    @SuppressLint("AutoDispose")
    private void getUnbindDevice() {
        SearchFoodImpl.getInstance().getUnbindDevice().subscribe(result -> {
            if (result.isSuccess()) {
                mDeviceList.clear();
                mDeviceList.addAll(result.data);
                if (mDeviceList.size() == 0) {
                    rvRecipeDevice.setVisibility(View.GONE);
                } else {
                    rvRecipeDevice.setVisibility(View.VISIBLE);
                    deviceAdapter.notifyDataSetChanged();
                }
            } else {
                Log.e("nail", "rsult error");
            }

        }, throwable -> {
            ToastUtils.getInstance().showCustomToast(throwable.getMessage());
        });
    }

    @SuppressLint("AutoDispose")
    private void initVedioRecipe() {
        ArrayList<RecipeHotBean> tpArr = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            RecipeHotBean recipeHotBean = new RecipeHotBean();
            recipeHotBean.setItemType(-1);
            tpArr.add(recipeHotBean);
        }
        recipeAdapter.addData(tpArr);
        SearchFoodImpl.getInstance().getVedioRecips(1, 5, "VIDEO", "RELEASE").subscribe(result -> {
            if (result.isSuccess()) {
                ArrayList<RecipeHotBean> tpDataArr = new ArrayList<>();

                recipeAdapter.stopListPlay();
                tpDataArr.addAll(result.data.rows);
                RecipeHotBean recipeHotBean = new RecipeHotBean();
                recipeHotBean.setItemType(RecipeHotBean.TYPE_LOAD);

                recipeAdapter.setList(tpDataArr);
            } else {
                ToastUtils.getInstance().showCustomToast(result.message);
            }

        }, throwable -> {
            ToastUtils.getInstance().showCustomToast(throwable.getMessage());
        });
    }

    @SuppressLint("AutoDispose")
    private void initFoodRecomonds() {
        SearchFoodImpl.getInstance().getFoodRecords(Constants.Fun.APP_TWO, 200).subscribe(result -> {
            if (result.isSuccess()) {
                mTopicList.clear();
                mTopicList.addAll(result.data.rows);
                topicAdapter.notifyDataSetChanged();
            } else {
                ToastUtils.getInstance().showCustomToast(result.message);
            }

        }, throwable -> {
            ToastUtils.getInstance().showCustomToast(throwable.getMessage());
        });
    }

    /**
     * 收藏食谱
     *
     * @param storeBean
     */
    @SuppressLint("AutoDispose")
    private void setRecipeStored(RecipeStoreBean storeBean) {
        SearchFoodImpl.getInstance().recipeStore(storeBean).subscribe(result -> {
            if (result.isSuccess()) {
                if (StatePositon == 1) {
                    originHotPage = 1;
                    initHotRecipe(deviceProductModel);
                } else {
                    originNewPage = 1;
                    initNewRecipe(deviceProductModel);
                }
            } else {
                ToastUtils.getInstance().showCustomToast(result.data);
            }
        }, throwable -> {
            ToastUtils.getInstance().showCustomToast(throwable.getMessage());
        });
    }

    /**
     * 取消收藏食谱
     *
     * @param favorateId
     */
    @SuppressLint("AutoDispose")
    private void cancleRecipeStored(int favorateId) {
        SearchFoodImpl.getInstance().cancleRecipeStore(favorateId).subscribe(result -> {
            if (result.isSuccess()) {
                if (StatePositon == 1) {
                    originHotPage = 1;
                    initHotRecipe(deviceProductModel);
                } else {
                    originNewPage = 1;
                    initNewRecipe(deviceProductModel);
                }
            } else {
                ToastUtils.getInstance().showCustomToast(result.data);
            }

        }, throwable -> {
            ToastUtils.getInstance().showCustomToast(throwable.getMessage());
        });
    }

    private void initVideoList() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
        rvRecordRecipe.setLayoutManager(linearLayoutManager);
        recipeAdapter = new RecomondRecipeAdapter();
        rvRecordRecipe.setAdapter(recipeAdapter);
        recipeAdapter.bindRecView(rvRecordRecipe);
        viewModel.getRecipeThumbsResult().observe(getActivity(), new Observer<BaseLocalConfigBean>() {
            @Override
            public void onChanged(BaseLocalConfigBean baseLocalConfigBean) {
                if (null != baseLocalConfigBean
                        && recipeAdapter.getData().size() > baseLocalConfigBean.getLocalPosition()) {
                    RecipeHotBean recipeHotBean = recipeAdapter.getData().get(baseLocalConfigBean.getLocalPosition());
                    if (!recipeHotBean.getRecipeId().equals(baseLocalConfigBean.getLocalId())) {
                        return;
                    }
                    recipeHotBean.setLikeCount(recipeHotBean.getLikeCount() + baseLocalConfigBean.getLocalType());
                    recipeHotBean.setIsLike(baseLocalConfigBean.getLocalType() > 0
                            ? 1 : 2);
                    ImageView ivLike = (ImageView) recipeAdapter
                            .getViewByPosition(baseLocalConfigBean.getLocalPosition(), R.id.iv_recipe_like);
                    if (null != ivLike) {
                        ivLike.setBackgroundResource(recipeHotBean.getIsLike() == 1
                                ? R.mipmap.like_icon_clicked : R.mipmap.like_icon_none);
                    }
                    TextView tvThumbNum = (TextView) recipeAdapter
                            .getViewByPosition(baseLocalConfigBean.getLocalPosition(), R.id.tv_recipe_like);
                    if (null != tvThumbNum) {
                        tvThumbNum.setText(NumberUtils.formatNum(recipeHotBean.getLikeCount()));
//                        tvThumbNum.setTextColor(recipeHotBean.getIsLike() == 1 ? 0xffff9b00 : 0xff999999);
                    }
                }
            }
        });
        recipeAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                if (recipeAdapter.getData().size() > position) {

                    if (view.getId() == R.id.iv_recipe_voice) {
                        recipeAdapter.getData().get(position).setLocalIsMuteEnb(recipeAdapter.getData().get(position).getLocalIsMuteEnb()
                                == 1 ? 0 : 1
                        );
                        view.setBackgroundResource(recipeAdapter.getData().get(position).getLocalIsMuteEnb() == 1 ?
                                R.mipmap.play_voice_icon : R.mipmap.play_voice_mute);

                        recipeAdapter.setVolume(position, recipeAdapter.getData().get(position).getLocalIsMuteEnb());
                    } else if (view.getId() == R.id.ll_rep_like) {
                        if (!passClick()) return;
                        if (AppAgent.isLogin() && null != GlobalDataCache.userInfo) {
                            RecipeHotBean recipeHotBean = recipeAdapter.getData().get(position);
                            if (recipeHotBean.getIsLike() == 1) {
                                viewModel.recipeThumbsDel(recipeHotBean.getRecipeId(), recipeHotBean.getLikeId(), position);
                            } else {
                                viewModel.recipeThumb(recipeHotBean.getRecipeId(), position);
                            }
                        }
                    } else if (view.getId() == R.id.ll_rep_sub) {
                        if (!passClick()) return;
                        if (AppAgent.isLogin() && null != GlobalDataCache.userInfo) {
                            final String addrId = recipeAdapter.getData().get(position).getRecipeId();
                            Observable<BaseApiResult<VideoFavoritBean>> observable;
                            if (recipeAdapter.getData().get(position).getFavoriteType() == 1) {
                                observable = VideoApiImpl.getInstance().subRecipeDel(addrId);
                            } else {
                                observable = VideoApiImpl.getInstance().subRecipe(addrId, GlobalDataCache.userInfo.getBossUserId());
                            }
                            observable.subscribeOn(Schedulers.io())
                                    .observeOn(AndroidSchedulers.mainThread())
//                                .to(autoDisposeConverter)
                                    .subscribe(new Consumer<BaseApiResult<VideoFavoritBean>>() {
                                        @Override
                                        public void accept(BaseApiResult<VideoFavoritBean> stringBaseApiResult) throws Exception {
                                            FavoritStateBean favoritStateBean = new FavoritStateBean();
                                            favoritStateBean.setId(addrId);
                                            favoritStateBean.setLocalCountType(1);
                                            favoritStateBean.setLocalPosition(position);
//                                            favoritResult.setValue(favoritStateBean);
                                            RecipeHotBean recipeHotBean = recipeAdapter.getData().get(position);

                                            if (recipeHotBean.getFavoriteType() == 1) {
                                                recipeHotBean.setFavoriteCount(recipeHotBean.getFavoriteCount() - 1);
                                                recipeHotBean.setFavoriteType(2);
                                                ImageView imageView = (ImageView) recipeAdapter.getViewByPosition(position, R.id.iv_recipe_store);
                                                if (null != imageView) {
                                                    imageView.setBackgroundResource(R.mipmap.ic_recipe_sub_gary);
                                                }
                                            } else {
                                                recipeHotBean.setFavoriteCount(recipeHotBean.getFavoriteCount() + 1);
                                                recipeHotBean.setFavoriteType(1);
                                                ImageView imageView = (ImageView) recipeAdapter.getViewByPosition(position, R.id.iv_recipe_store);
                                                if (null != imageView) {
                                                    imageView.setBackgroundResource(R.mipmap.stored_icon);
                                                }
                                            }
                                        }
                                    }, new Consumer<Throwable>() {
                                        @Override
                                        public void accept(Throwable throwable) throws Exception {
//                        favoritResult.setValue(new Result.Error(new Exception(throwable)));
                                        }
                                    });
                        }
                    }
                }
            }
        });
        recipeAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (recipeAdapter.getData().size() > position) {

                if (recipeAdapter.getData().get(position).getItemType() == RecipeHotBean.TYPE_ITEM) {
                    RecipeHotBean bean = recipeAdapter.getData().get(position);
                    AppAgent.startRecipePage(bean.getRecipeId(), bean.getModelId());
                } else {
                    ARouter.getInstance().build(PathUrl.PATH_MD_VIDEO_LIST)
                            .withTransition(com.android.baseconfig.R.anim.activity_open_enter,
                                    com.android.baseconfig.R.anim.activity_open_exit)
                            .navigation(FoodRootFragment.this.getContext());
                }
            }
        });

//        smartRefreshHorizontal.setOnLoadMoreListener(new OnLoadMoreListener() {
//            @Override
//            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
//
//            }
//        });
    }

    private void initRecycleView() {
        StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        bindingView.rvRecipeList.setLayoutManager(staggeredGridLayoutManager);
        //将上部分布局改为headrview
        View headerView = getLayoutInflater().inflate(R.layout.food_fragment_head, bindingView.rvRecipeList, false);
        rlNoneResult = getLayoutInflater().inflate(R.layout.item_none_result, bindingView.rvRecipeList, false);
        ivRecipeAll = headerView.findViewById(R.id.iv_recipe_all);
        ivFruitEggs = headerView.findViewById(R.id.iv_fruit_eggs);
        ivMainFood = headerView.findViewById(R.id.iv_main_food);
        ivMeatMean = headerView.findViewById(R.id.iv_meat_mean);
        ivSeaFood = headerView.findViewById(R.id.iv_sea_food);
        edtFoodInput = headerView.findViewById(R.id.edt_food_input);
        ivScan = headerView.findViewById(R.id.iv_scan);
        rvRecordRecipe = headerView.findViewById(R.id.rv_record_recipe);
//        smartRefreshHorizontal = headerView.findViewById(R.id.smartRefreshHorizontal);
        rvRecipeClass = headerView.findViewById(R.id.rv_recipe_class);
        rvRecipeCooker = headerView.findViewById(R.id.rv_recipe_cookers);
        rvRecipeDevice = headerView.findViewById(R.id.rv_recipe_device);
        tvRecipeHot = headerView.findViewById(R.id.tv_recipe_hot);
        tvRecipeNew = headerView.findViewById(R.id.tv_recipe_new);

        //获取到headerview中的子控件
        bindingView.rvRecipeList.addHeaderView(headerView);
        bindingView.rvRecipeList.setFocusableInTouchMode(false);
        bindingView.rvRecipeList.setFocusable(false);
        bindingView.rvRecipeList.setHasFixedSize(true);

        initVideoList();
        topicAdapter = new RecipeTopicAdapter(mTopicList, getActivity());
        cookerAdapter = new RecipeChefAdapter(mCookerList, getActivity());
        deviceAdapter = new RecipeDeviceAdapter(mDeviceList, getActivity(), (int position, boolean state) -> {
            deviceAdapter.setPosition(position);
            if (!state) {
                deviceProductModel = mDeviceList.get(position).getModelTypeId();
            } else {
                deviceProductModel = "";
            }
            originNewPage = 1;
            originHotPage = 1;
            if (StatePositon == 1) {
                initHotRecipe(deviceProductModel);
            } else {
                initNewRecipe(deviceProductModel);
            }
        });
        noneResultAdapter = new RecipeNoneResultAdapter(getActivity());
        hotAdapter = new RecipeHotAdapter(mHotList, getActivity());
        hotAdapter.setShowName(true);
        hotAdapter.setUnlike(true);
        hotAdapter.setRecipeHotListener(new RecipeHotAdapter.OnClassifyClickListener() {
            @Override
            public void OnItemClick(int position) {
                RecipeHotBean bean = mHotList.get(position);
                if (AppAgent.h5Debug) {
                    AppAgent.startDebugTiny(activity, Constants.App.PAGE_RECIPE, "",
                            "id=" + bean.getRecipeId());
                } else {
                    AppAgent.startRecipePage(bean.getRecipeId(), bean.getModelId());
                }
            }

            @Override
            public void OnItemLongClick(int position) {
                Log.e("nail", "OnItemLongClick");
            }

            @Override
            public void OnAvatarClick(int position) {
                RecipeHotBean hotBean = mHotList.get(position);
                if (!TextUtils.isEmpty(hotBean.getChefId())) {
                    Intent intent = new Intent(getActivity(), CookerHomeActivity.class);
                    intent.putExtra(CHEF_ID, hotBean.getChefId());
                    startActivity(intent);
                } else {
                    ToastUtils.getInstance().showCustomToast(R.string.check_error);
                }
            }

            @Override
            public void OnStarClick(int position) {

                RecipeHotBean bean = mHotList.get(position);
                int state = bean.getFavoriteType();
                if (AppAgent.isLogin()) {
                    if (state == 1) {
                        cancleRecipeStored(bean.getFavoriteId());
                    } else {
                        RecipeStoreBean storeBean = new RecipeStoreBean();
                        storeBean.setAddrId(bean.getRecipeId());
                        storeBean.setFavoriteAddr("RECIPE_ID");
                        setRecipeStored(storeBean);
                    }
                } else {
                    SuporPresenter.getInstance().getCmccHelper().displayLogin(true);
                }
            }

            @Override
            public void OnUnlikeRecipe(int position) {

            }

            @Override
            public void OnUnlikeClassify(int position) {

            }
        });
        //LoadMoreWrapper hotWrapper = new LoadMoreWrapper(hotAdapter);
        bindingView.rvRecipeList.setAdapter(hotAdapter);

        LinearLayoutManager linearLayoutManager2 = new LinearLayoutManager(getActivity());
        linearLayoutManager2.setOrientation(RecyclerView.HORIZONTAL);
        rvRecipeClass.setAdapter(topicAdapter);
        rvRecipeClass.setLayoutManager(linearLayoutManager2);

        LinearLayoutManager linearLayoutManager4 = new LinearLayoutManager(getActivity());
        linearLayoutManager4.setOrientation(RecyclerView.HORIZONTAL);
        rvRecipeCooker.setAdapter(cookerAdapter);
        rvRecipeCooker.setLayoutManager(linearLayoutManager4);

        LinearLayoutManager linearLayoutManager3 = new LinearLayoutManager(getActivity());
        linearLayoutManager3.setOrientation(RecyclerView.HORIZONTAL);
        rvRecipeDevice.setAdapter(deviceAdapter);
        rvRecipeDevice.setLayoutManager(linearLayoutManager3);


        tvRecipeHot.setOnClickListener(this);
        tvRecipeNew.setOnClickListener(this);
    }


    private void changeState(int position) {
        StatePositon = position;
        if (position == 0) {
            tvRecipeHot.setTextColor(getActivity().getResources().getColor(R.color.content_assist));
            tvRecipeHot.setTextSize(TypedValue.COMPLEX_UNIT_PX, getActivity().getResources().getDimension(R.dimen.sp_14));
            tvRecipeNew.setTextColor(getActivity().getResources().getColor(R.color.content_default));
            tvRecipeNew.setTextSize(TypedValue.COMPLEX_UNIT_PX, getActivity().getResources().getDimension(R.dimen.sp_17));
            tvRecipeNew.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
            tvRecipeHot.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            originNewPage = 1;
            initNewRecipe(deviceProductModel);
        } else if (position == 1) {
            tvRecipeNew.setTextColor(getActivity().getResources().getColor(R.color.content_assist));
            tvRecipeNew.setTextSize(TypedValue.COMPLEX_UNIT_PX, getActivity().getResources().getDimension(R.dimen.sp_14));
            tvRecipeHot.setTextColor(getActivity().getResources().getColor(R.color.content_default));
            tvRecipeHot.setTextSize(TypedValue.COMPLEX_UNIT_PX, getActivity().getResources().getDimension(R.dimen.sp_17));
            tvRecipeHot.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
            tvRecipeNew.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            originHotPage = 1;
            initHotRecipe(deviceProductModel);
        }
    }

    private void initClassify(String classify) {
        for (int i = 0; i < mClassifyList.size(); i++) {
            if (mClassifyList.get(i).getClassificationName().equals(classify)) {
                Intent intent = new Intent(getActivity(), RecipeTagsActivity.class);
                intent.putExtra(CLASSIFY_SECOND_DATA, mClassifyList.get(i));
                intent.putExtra(CLASSIFY_SECOND_POSITION, 0);
                getActivity().startActivity(intent);
            }
        }
    }

    @Override
    public int setContent() {
        return R.layout.food_fragment_root;
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.tv_recipe_hot) {
            if (DoubleClickUtils.isFastDoubleClick()) return;
            changeState(1);
        } else if (view.getId() == R.id.tv_recipe_new) {
            if (DoubleClickUtils.isFastDoubleClick()) return;
            changeState(0);
        } else if (view.getId() == R.id.iv_recipe_all) {
            if (DoubleClickUtils.isFastDoubleClick()) return;
            Intent intent = new Intent(getActivity(), ClassifyActivity.class);
            intent.putExtra(CLASSIFY_DATA, (Serializable) mClassifyList);
            getActivity().startActivity(intent);
        } else if (view.getId() == R.id.iv_meat_mean) {
            if (DoubleClickUtils.isFastDoubleClick()) return;
            initClassify(getActivity().getResources().getString(R.string.meat_mean));
        } else if (view.getId() == R.id.iv_main_food) {
            if (DoubleClickUtils.isFastDoubleClick()) return;
            initClassify(getActivity().getResources().getString(R.string.main_food));
        } else if (view.getId() == R.id.iv_sea_food) {
            if (DoubleClickUtils.isFastDoubleClick()) return;
            initClassify(getActivity().getResources().getString(R.string.sea_food));
        } else if (view.getId() == R.id.iv_fruit_eggs) {
            if (DoubleClickUtils.isFastDoubleClick()) return;
            initClassify(getActivity().getResources().getString(R.string.fruit_eggs));
        } else if (view.getId() == R.id.edt_food_input) {
            if (DoubleClickUtils.isFastDoubleClick()) return;
            Intent intent = new Intent(getActivity(), IntoSearchActivity.class);
            intent.putExtra(RECOMOND_WORD, recomondWord);
            getActivity().startActivity(intent);
        } else if (view.getId() == R.id.iv_scan) {
            if (DoubleClickUtils.isFastDoubleClick()) return;
            // gotoScanActivity();
        }

    }

    @Override
    public void onPause() {
        super.onPause();
//        if (null != videoScrollPlayerManager) {
//            videoScrollPlayerManager.onPause();
//        }
        if (null != recipeAdapter) {
            recipeAdapter.onPause();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
//        if (null != videoScrollPlayerManager) {
//            videoScrollPlayerManager.onResume();
//        }
//        bindingView.food.smoothScrollTo(0,0);
        if (null != recipeAdapter) {
            recipeAdapter.onResume();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        RxBus3.getInstance().unregister(this.getClass());
    }

    private long lastClick;

    /**
     * [防止快速点击]
     *
     * @return
     */
    public boolean passClick() {
        if (System.currentTimeMillis() - lastClick <= 1000) {
            return false;
        }
        lastClick = System.currentTimeMillis();
        return true;
    }
}

